<template>
  <view class="container" style="display: flex; flex-direction: column; height: 100vh;">
    <!-- 顶部导航栏 -->
    <view class="detail-header" :class="{ 'sticky': isHeaderSticky }">
      <view class="nav-left">
        <uni-icons type="arrowleft" size="24" color="#333" @click="goBack"></uni-icons>
      </view>
      <view class="nav-tabs">
        <view
            v-for="tab in detailTabs"
            :key="tab"
            :class="['nav-tab', activeTab === tab ? 'active' : '']"
            @click="switchTab(tab)"
        >
          {{ tab }}
        </view>
      </view>
      <view class="nav-right">
        <uni-icons type="home" size="20" color="#333" class="nav-icon"></uni-icons>
      </view>
    </view>

    <!-- 内容滚动区域 -->
    <scroll-view scroll-y class="content-scroll" @scroll="onScroll" :scroll-top="scrollViewTop" :scroll-with-animation="true" style="min-height: 100vh">
      <!-- 商品画廊 -->
      <view id="goods-section" class="goods-gallery">
        <swiper :autoplay="false" :circular="true" class="gallery-swiper" @change="onSwiperChange">
          <swiper-item v-for="(img, index) in goods.images" :key="index">
            <image :src="img" class="gallery-image" mode="aspectFit"></image>
          </swiper-item>
        </swiper>
        <view class="gallery-pagination">
          {{ currentImage }}/{{ goods.images.length }}
        </view>
        <view class="badge-classic">经典</view>
      </view>

      <!-- 商品基本信息 -->
      <view class="goods-basic-info">
        <view class="goods-header">
          <view class="goods-title">{{ goods.title }}</view>
          <view class="share-icon">
            <uni-icons type="redo" size="20" color="#999"></uni-icons>
            <text>分享</text>
          </view>
        </view>

        <view class="price-rank">
          <view class="price-range">¥{{ selectedSkuPrice }}</view>
          <view class="goods-rank">店铺商品热榜第{{ goods.rank }}名</view>
        </view>

        <view class="vip-banner">
          <text class="vip-title">大王卡2025可享2大权益</text>
          <button class="vip-btn">立即尊享</button>
        </view>

        <view class="goods-meta">
          <text class="meta-item">运费 ￥{{ goods.shippingFeeRange.min }} - ￥{{ goods.shippingFeeRange.max }}</text>
          <text class="meta-item">已售{{ goods.sold }} | 剩余{{ goods.stock }}</text>
          <text class="meta-item">服务: 支持退换 · 7天无理由退货 · 线下门店</text>
        </view>
      </view>

      <!-- 规格选择 -->
      <view id="sku-section" class="sku-section">
        <view class="section-header">
          <text class="section-title">选择型号</text>
          <text class="section-sub">共{{ goods.skus.length }}种型号可选</text>
        </view>

        <scroll-view scroll-x class="sku-scroll">
          <view class="sku-column" v-for="(chunk, index) in chunkedSkus" :key="index">
            <view
                v-for="sku in chunk"
                :key="sku.id"
                :class="['sku-option', activeSku === sku.id ? 'active' : '']"
                @click="selectSku(sku.id)"
            >
              {{ sku.name }}
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 评价区域 -->
      <view id="review-section" class="review-section">
        <view class="section-header">
          <text class="section-title">商品评价</text>
          <text class="see-all">暂无评价 ></text>
        </view>
        <view class="no-reviews">
          <text>暂无评价信息</text>
        </view>
      </view>

      <!-- 详情区域 -->
      <view id="detail-section" class="detail-section">
        <view class="section-header">
          <text class="section-title">商品详情</text>
        </view>

        <view class="detail-content">
          <view class="detail-item" v-for="(desc, index) in goods.description" :key="index">
            <view class="detail-title">{{ desc.title }}</view>
            <view class="detail-text">{{ desc.content }}</view>
          </view>
        </view>
      </view>

      <!-- 推荐区域 -->
      <view id="recommend-section" class="recommend-section">
        <view class="section-header">
          <text class="section-title">为你推荐</text>
        </view>

        <scroll-view scroll-x class="recommend-scroll">
          <view class="recommend-item" v-for="(item, index) in recommendedGoods" :key="index">
            <image :src="item.image" class="recommend-image"></image>
            <view class="recommend-title">{{ item.title }}</view>
            <view class="recommend-price">¥{{ item.price }}</view>
          </view>
        </scroll-view>
      </view>

      <!-- 底部操作栏 -->
      <view class="action-bar">
        <view class="action-icon">
          <image src="/static/img/chat.png" class="action-icon-img" mode="aspectFit"></image>
          <text class="icon-text">客服</text>
        </view>
        <view class="action-icon">
          <image src="/static/img/shop.png" class="action-icon-img" mode="aspectFit"></image>
          <text class="icon-text">店铺</text>
        </view>
        <view class="action-icon" @click="goToCart">
          <uni-badge :text="cartCount" :is-dot="cartCount > 0" size="small" absolute="rightTop">
            <image src="/static/img/cart.png" class="action-icon-img" mode="aspectFit"></image>
          </uni-badge>
          <text class="icon-text">购物车</text>
        </view>


        <view class="action-buttons">
          <button class="add-cart-btn" @click="addToCart">加入购物车</button>
          <button class="buy-now-btn" @click="buyNow">立即购买</button>
        </view>
      </view>

      <!-- 加入购物车提示 -->
      <uni-popup ref="popup" type="message">
        <uni-popup-message type="success" message="已加入购物车" :duration="2000"></uni-popup-message>
      </uni-popup>
    </scroll-view>
  </view>
</template>


<script setup>
  import { ref, reactive, computed, onMounted } from 'vue';

  // 当前活动的标签页
  const activeTab = ref('商品');

  // 是否吸顶
  const isHeaderSticky = ref(false);

  // 当前活动SKU
  const activeSku = ref('s1');

  // 商品数据
  const goods = reactive({
  id: 'g001',
  title: '【漾粉福利社】速干王胶水，丝滑手感，1秒速干，牢固70天',
  minPrice: 120,
  maxPrice: 240,
  images: [
  'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk=',
  'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk=',
  'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk='
  ],
  rank: 20,
  sold: 743,
  stock: 1042,
  shippingFeeRange: {
  min: 6,
  max: 18
},
  skus: [
{id: 's1', name: '经典-速干王(1大瓶)', price: 120},
{id: 's2', name: '经典-速干王(1大瓶+1小瓶)', price: 140},
{id: 's3', name: '经典-速干王(1大瓶+2小瓶)', price: 152},
{id: 's4', name: '经典-速干王(2大瓶)', price: 230},
{id: 's5', name: '经典-速干王(3大瓶)', price: 330},
{id: 's6', name: '防泪-速干王(1大瓶)', price: 130},
{id: 's7', name: '防泪-速干王(1大瓶+1小瓶)', price: 150},
{id: 's8', name: '防泪-速干王(1大瓶+2小瓶)', price: 162},
{id: 's9', name: '防泪-速干王(2大瓶)', price: 240},
{id: 's10', name: '防泪-速干王(3大瓶)', price: 340}
  ],
  description: [
{
  title: '产品特色',
  content: '速干王胶水采用最新技术，丝滑手感，1秒速干，牢固70天。适用于各种假睫毛类型，无刺激性气味，防水防汗，持久耐用。'
},
{
  title: '使用方法',
  content: '1. 清洁并干燥眼部区域\n2. 取适量胶水均匀涂抹在假睫毛根部\n3. 等待10-15秒胶水稍干\n4. 将假睫毛轻轻贴在睫毛根部\n5. 轻轻按压10秒使其牢固'
},
{
  title: '注意事项',
  content: '避免接触眼睛。若不慎入眼，立即用大量清水冲洗。置于儿童无法触及处。请存放于阴凉干燥处，避免阳光直射。'
}
  ]
});

  // 推荐商品数据
  const recommendedGoods = reactive([
  {
    id: 'g002',
    title: '国风L婴儿弯睫毛',
    price: 45,
    image: 'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk='
  },
  {
    id: 'g003',
    title: '0.05圆毛多根开花',
    price: 48,
    image: 'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk='
  },
  {
    id: 'g004',
    title: '黛毛上妆液',
    price: 78,
    image: 'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk='
  },
  {
    id: 'g005',
    title: '假睫毛卸除液',
    price: 68,
    image: 'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk='
  }
  ]);

  // 标签页选项
  const detailTabs = ['商品', '评价', '详情', '推荐'];

  // 购物车商品数量
  const cartCount = ref(0);

  // 当前显示的图片索引
  const currentImage = ref(1);

  // 当前选中SKU的价格
  const selectedSkuPrice = computed(() => {
  const sku = goods.skus.find(s => s.id === activeSku.value);
  return sku ? sku.price : goods.minPrice;
});

  // 模块定位数组
  const sectionPositions = ref([]);


  let ticking = false;

  const onScroll = (e) => {
    const scrollTop = e.detail.scrollTop;

    isHeaderSticky.value = scrollTop > 50;

    if (!ticking) {
      setTimeout(() => {
        const sectionIds = ['goods-section', 'review-section', 'detail-section', 'recommend-section'];
        let found = false;

        for (let i = sectionIds.length - 1; i >= 0; i--) {
          const id = sectionIds[i];
          const offsetTop = modulePositions.value[id];

          if (offsetTop && !found && scrollTop >= offsetTop - 100) {
            found = true;
            activeTab.value = ['商品', '评价', '详情', '推荐'][i];
          }
        }

        ticking = false;
      }, 0);

      ticking = true;
    }
  };







  // 选择SKU
  const selectSku = (skuId) => {
  activeSku.value = skuId;
};
  const scrollViewTop = ref(0);
  // 切换标签页并滚动到对应模块
  const switchTab = (tab) => {
    activeTab.value = tab;

    const index = detailTabs.indexOf(tab);
    if (index >= 0) {
      const targetId = ['goods-section', 'review-section', 'detail-section', 'recommend-section'][index];

      setTimeout(() => {
        uni.createSelectorQuery()
            .select(`#${targetId}`)
            .boundingClientRect(res => {
              if (res) {
                // 更新缓存中的位置
                modulePositions.value[targetId] = res.top;

                setTimeout(() => {
                  scrollViewTop.value = res.top - 100;
                }, 30);
              } else {
                uni.showToast({ title: '找不到该模块', icon: 'none' });
              }
            })
            .exec();
      }, 50);
    }
  };








  // 图片切换更新页码
  const onSwiperChange = (e) => {
  currentImage.value = e.detail.current + 1;
};

  // 添加到购物车
  const addToCart = () => {
  cartCount.value++;
  uni.showToast({ title: '已加入购物车', icon: 'success' });
};

  // 立即购买
  const buyNow = () => {
  uni.navigateTo({ url: '/pages/order/confirm' });
};

  // 前往购物车
  const goToCart = () => {
  uni.switchTab({ url: '/pages/cart/cart' });
};

  // 返回上一页
  const goBack = () => {
  uni.navigateBack();
};

  // 分块 SKU
  const chunkedSkus = computed(() => {
  const result = [];
  for (let i = 0; i < goods.skus.length; i += 2) {
  result.push(goods.skus.slice(i, i + 2));
}
  return result;
});

  // 页面加载获取模块位置
  onMounted(() => {
 updateModulePositions()

});

  const modulePositions = ref({});

  const updateModulePositions = () => {
    const ids = ['goods-section', 'review-section', 'detail-section', 'recommend-section'];
    ids.forEach((id, i) => {
      uni.createSelectorQuery()
          .select(`#${id}`)
          .boundingClientRect(res => {
            if (res) {
              modulePositions.value[id] = res.top;
            }
          })
          .exec();
    });
  };




  // 手动刷新
  const refreshPositions = () => {
    updateModulePositions();
  };

</script>
<style lang="scss" scoped>
.container {
  padding-bottom: 100px;
  background-color: #f8f8f8;
}

.detail-header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  padding: 10px 16px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.nav-left,
.nav-right {
  width: 40px;
}

.nav-tabs {
  flex: 1;
  display: flex;
  justify-content: space-around;
}

.nav-tab {
  font-size: 16px;
  padding: 6px 0;
  position: relative;
  color: #666;

  &.active {
    font-weight: 600;
    color: #e54d42;

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 24px;
      height: 3px;
      background-color: #e54d42;
      border-radius: 2px;
    }
  }
}

.goods-gallery {
  position: relative;
  height: 380px;
  background: linear-gradient(135deg, #f0f0f0, #e0e0e0);
}

.gallery-swiper,
.gallery-image {
  width: 100%;
  height: 100%;
}

.gallery-pagination {
  position: absolute;
  right: 16px;
  bottom: 16px;
  background-color: rgba(0, 0, 0, 0.4);
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
}

.badge-classic {
  position: absolute;
  top: 16px;
  right: 16px;
  background-color: #e54d42;
  color: white;
  padding: 4px 16px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
}

.goods-basic-info {
  background-color: #fff;
  padding: 16px;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.goods-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.goods-title {
  font-size: 18px;
  font-weight: bold;
  line-height: 1.4;
  flex: 1;
}

.share-icon {
  width: 50px;
  text-align: center;
  color: #999;
  font-size: 12px;
}

.price-rank {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.price-range {
  font-size: 22px;
  font-weight: bold;
  color: #e54d42;
  margin-right: 15px;
}

.goods-rank {
  background-color: #fff9eb;
  color: #ff9d00;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
}

.vip-banner {
  background: linear-gradient(90deg, #ffebd6, #fff7eb);
  border-radius: 8px;
  padding: 12px;
  font-size: 13px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.vip-title {
  color: #e54d42;
  font-weight: 600;
}

.vip-btn {
  background: linear-gradient(90deg, #ff9d6c, #ff6b6b);
  color: white;
  font-size: 12px;
  height: 32px;
  line-height: 32px;
  padding: 0 12px;
  border-radius: 16px;
}

.goods-meta {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #eee;
}

.meta-item {
  display: block;
  margin-bottom: 6px;
  font-size: 13px;
  color: #666;
}

.sku-section,
.review-section,
.detail-section,
.recommend-section {
  background-color: #fff;
  margin: 16px;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  margin-bottom: 120px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
}

.section-sub {
  font-size: 13px;
  color: #999;
}

.sku-scroll {
  white-space: nowrap;
  padding-bottom: 5px;
}

.sku-column {
  display: flex;
  flex-direction: column;
  margin-right: 10px;
}

.sku-option {
  display: inline-block;
  padding: 8px 16px;
  background-color: #f5f5f5;
  border-radius: 18px;
  font-size: 13px;
  margin-bottom: 10px;

  &.active {
    background-color: #fff0f0;
    color: #e54d42;
    border: 1px solid #e54d42;
  }
}

.no-reviews {
  padding: 40px 0;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.detail-content {
  padding-top: 10px;
}

.detail-item {
  margin-bottom: 20px;
}

.detail-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.detail-text {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  white-space: pre-wrap;
}

.recommend-scroll {
  white-space: nowrap;
  padding-bottom: 10px;
}

.recommend-item {
  display: inline-block;
  width: 120px;
  margin-right: 12px;
}

.recommend-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
}

.recommend-title {
  font-size: 13px;
  margin-top: 6px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 36px;
  line-height: 18px;
  white-space: normal;
}

.recommend-price {
  font-size: 15px;
  color: #e54d42;
  font-weight: bold;
  margin-top: 4px;
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 10px 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.action-icons {
  display: flex;
  align-items: center;
  flex: 1;
}
.action-icon {
  text-align: center;
  margin-right: 12px;
  font-size: 12px;
  color: #666;
  position: relative;
  width: 50px;

  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.icon-text {
  display: block;
  font-size: 10px;
  margin-top: 2px;
}

.action-buttons {
  flex: 2;
  display: flex;
}

.add-cart-btn,
.buy-now-btn {
  flex: 1;
  height: 46px;
  border-radius: 30px;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.add-cart-btn {
  background: linear-gradient(90deg, #ff9d6c, #ff6b6b);
  color: white;
  margin-right: 10px;
}

.buy-now-btn {
  background: linear-gradient(90deg, #e54d42, #d03a2f);
  color: white;
}
.action-icon-img {
  width: 20px;
  height: 20px;
  display: block;
}

</style>